

package cn.shengchao.page;

import cn.hutool.core.util.StrUtil;
import cn.shengchao.base.utils.HttpKit;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

import java.util.List;
import java.util.function.Supplier;

/**
 * Created by
 *
 * @author sheng
 * @date 18/3/16.
 */
public class PageFactory {

    public static <T> List<T> page(Supplier<List<T>> supplier) {
        int pageNo;
        int pageSize;
        try {
            pageSize = Integer.parseInt(HttpKit.getRequestParameters().get("pageSize"));
            pageNo = Integer.parseInt(HttpKit.getRequestParameters().get("pageNo"));
        } catch (Exception e) {
            try {
                pageSize = Integer.parseInt(HttpKit.getRequestParameters().get("size"));
                pageNo = Integer.parseInt(HttpKit.getRequestParameters().get("page"));
            } catch (Exception e1) {
                pageSize = 1000000000;
                pageNo = 1;
            }
        }
        String orderBy = sort();
        List<T> result;
        try (Page<Object> page = PageHelper.startPage(pageNo, pageSize, orderBy)) {
            result = supplier.get();
            HttpKit.getRequest().setAttribute("total", page.getTotal());
        }
        return result;
    }

    private static String sort() {
        String orderBy = "";
        // 获取排序字段
        String sort = HttpKit.getRequestParameters().get("sort");
        if (StrUtil.isNotEmpty(sort)) {
            // asc_class_asc_orderid
            String[] sorts = sort.split("_");
            for (int i = 0; i < sorts.length - 1; i = i + 2) {
                orderBy += sorts[i + 1] + " " + sorts[i] + " ";
            }
        }
        return orderBy;
    }
}
